// Copyright (c) 2012 NetPipe
// All Rights Reserved.

/**
 * @file XFile.h
 * 字符串相关方法
 * @author fanpc
 * @date 2012/07/25
 * @version 1.0
 * @note Create
 * Date		     Ver	     Name	   Description
 * 20120725		 1.1.0		 fanpc	   create
 */

#ifndef NP_UTILS_XSTRING_H
#define NP_UTILS_XSTRING_H

#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
#include <string>
#include <string.h>
#define SIZE_INT  128

using namespace std;
class XString
{
public:
  XString();

  static void replaceAll(std::string& str, const std::string& old_value, const std::string& new_value)
  {
    for(std::string::size_type pos(0); pos!=std::string::npos; pos+=new_value.length())
    {
      if((pos = str.find(old_value, pos)) !=std::string::npos)
      {
        str.replace(pos,old_value.length(),new_value);
      }
      else
      {
        break;
      }
    }
  }

  static std::vector<std::string> split(std::string str,std::string pattern)
  {
    std::string::size_type pos;
    std::string::size_type begin = 0;
    std::vector<std::string> result;
    while((pos=str.find(pattern,begin))!=std::string::npos)
    {
      result.push_back(str.substr(begin,pos-begin));
      begin =pos+1;
    }
    result.push_back(str.substr(begin,pos-begin-1));
    return result;
  }

  static int gbk2utf8(char *utfStr,const char *srcStr,int maxUtfStrlen)
  {
    if(NULL==srcStr)
    {
      printf("Bad Parameter\n");
      return -1;
    }

    //首先先将gbk编码转换为unicode编码
    if(NULL==setlocale(LC_ALL,"zh_CN.gbk"))//设置转换为unicode前的码,当前为gbk编码
    {
      printf("Bad Parameter\n");
      return -1;
    }

    int unicodeLen=mbstowcs(NULL,srcStr,0);//计算转换后的长度
    if(unicodeLen<=0)
    {
      printf("Can not Transfer!!!\n");
      return -1;
    }
    wchar_t *unicodeStr=(wchar_t *)calloc(sizeof(wchar_t),unicodeLen+1);
    mbstowcs(unicodeStr,srcStr,strlen(srcStr));//将gbk转换为unicode

    //将unicode编码转换为utf8编码
    if(NULL==setlocale(LC_ALL,"zh_CN.utf8"))//设置unicode转换后的码,当前为utf8
    {
      printf("Bad Parameter\n");
      return -1;
    }
    int utfLen=wcstombs(NULL,unicodeStr,0);//计算转换后的长度
    if(utfLen<=0)
    {
      printf("Can not Transfer!!!\n");
      return -1;
    }
    else if(utfLen>=maxUtfStrlen)//判断空间是否足够
    {
      printf("Dst Str memory not enough\n");
      return -1;
    }
    wcstombs(utfStr,unicodeStr,utfLen);
    utfStr[utfLen]=0;//添加结束符
    free(unicodeStr);
    return utfLen;
  }

};

#endif // NP_UTILS_XSTRING_H
